package com.code.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.beans.PropertyDescriptor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

public class ExcelUtil {

    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    public static Workbook getWorkBook(File file) throws IOException {
        //这样写  excel 能兼容03和07
        FileInputStream is = new FileInputStream(file);
        Workbook hssfWorkbook = null;
        try {
            if (isExcel2007(file.getPath())) {
                hssfWorkbook = new XSSFWorkbook(is);
            } else {
                hssfWorkbook = new HSSFWorkbook(is);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return hssfWorkbook;
    }

    public static void getWrongInfo(StringBuilder sb, List list, int i, Object obj, String name, String msg) throws Exception {
        Class clazz = obj.getClass();
        Object str = null;
        //得到属性名数组
        Field[] fields = clazz.getDeclaredFields();
        for (Field f : fields) {
            if (f.getName().equals(name)) {
                //用来得到属性的get和set方法
                PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
                //得到get方法
                Method getMethod = pd.getReadMethod();
                str = getMethod.invoke(obj);
            }
        }
        if (i == 0) {
            sb.append(msg).append(str).append(";");
        } else if (i == (list.size() - 1)) {
            sb.append(str).append("</br>");
        } else {
            sb.append(str).append(";");
        }
    }


    public static void downLoadExcel(String fileName, Workbook workbook) {
        String path = System.getProperty("user.dir");
        path = path + "\\script\\dbservice\\";
        System.out.println("EXCEL路径===========================" + path);
        try {
            FileOutputStream fos = new FileOutputStream(path + fileName);
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
